<template>
  <div class="dev-helper well" :class="{open:open}">
    <div class="open-btn" @click="open = !open"><i v-show="open" class="fa fa-angle-right" aria-hidden="true"></i><i v-show="!open" class="fa fa-angle-left" aria-hidden="true"></i></div>
    <div style="
      position: relative;
      width: 100%;
      height: 100%;
    ">
      <div class="actions" ref="actions">➤</div>
      <div class="input" ref="input"></div>
      <div class="output" ref="output"></div>
    </div>
  </div>
</template>

<script>
import SenseEditor from 'sense/src/sense_editor/editor'
import Autocomplete from 'sense/src/autocomplete'
import ace from 'ace'
import axios from 'axios'
import * as $ from 'jquery'

import {bus} from '@/bus.js'

export default {
  name: 'DevHelper',
  data () {
    return {
      open: false,
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted () {
    var self = this
    $(this.$refs.input)
    //     .text(`GET _search
    // {
    //   "query": {
    //     "match_all": {}
    //   }
    // }`)
    var input = new SenseEditor($(this.$refs.input))

    input.$actions = $(this.$refs.actions)

    input.autocomplete = new Autocomplete(input)

    input.commands.addCommand({
      name: 'auto indent request',
      bindKey: {win: 'Ctrl-I', mac: 'Command-I'},
      exec: function () {
        input.autoIndent()
      }
    })

    input.commands.addCommand({
      name: 'move to previous request start or end',
      bindKey: {win: 'Ctrl-Up', mac: 'Command-Up'},
      exec: function () {
        input.moveToPreviousRequestEdge()
      }
    })

    input.commands.addCommand({
      name: 'move to next request start or end',
      bindKey: {win: 'Ctrl-Down', mac: 'Command-Down'},
      exec: function () {
        input.moveToNextRequestEdge()
      }
    })

    function handelCkick () {
      self.execute()
    }

    $(this.$refs.actions).click(function () {
      handelCkick()
    })

    var output = ace.require('ace/ace').edit(this.$refs.output)
    output.getSession().setMode('ace/mode/json')
    output.setReadOnly(true)

    this.$_input = input
    this.$_output = output

    bus.$on('executeNewReq', req => {
      var string = input.getValue()

      if (string) {
        string += '\n\n'
      }

      string += req.method + ' ' + req.url
      if (req.data) {
        string += '\n' + JSON.stringify(req.data, null, 2)
      }
      input.setValue(string)
      input.moveToPreviousRequestEdge()
      input.moveToNextRequestEdge()
      // input.moveCursorTo(0, 0)
    })
  },
  methods: {
    execute () {
      var input = this.$_input
      var output = this.$_output
      input.getRequestsInRange(function (requests) {
        console.log(requests)
        // alert(requests[0].data)
        var plist = []
        var clist = []

        requests.forEach(function (d) {
          var string = d.method + ' ' + d.url + '\n'
          try {
            string += d.data.toString() + '\n'
          } catch (error) {
            // do nothing
          }

          clist.push(string)
          var data = null

          try {
            data = JSON.parse(d.data)
          } catch (error) {
            // do nothing
          }

          plist.push(axios.request({
            method: d.method === 'GET' && data ? 'POST' : d.method,
            url: d.url,
            data: data
          }))
        })

        Promise.all(plist).then(function (ress) {
          var result = ''

          ress.forEach((res, i) => {
            result += clist[i] + 'response:\n' + JSON.stringify(res.data, null, 2) + '\n\n'
          })

          output.setValue(result)
          output.moveCursorTo(0, 0)
        })
      })
    }
  }
}
</script>
<style scoped>
  .hello {
    padding: 0px;
  }

  .input {
    border-right: 1px solid #ccc;
  }

  .input,
  .output {
    float: left;
    width: 50%;
    height: 100%;
  }

  .actions {
    position: absolute;
    z-index: 100;
    right: 51%;
    margin-right: 0px;
    margin-top: -3px;
    cursor: pointer;
    color: green;
  }
</style>
